package com.tr.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.tr.gateway.service.RemoteSsoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class SsoLoginFilter  implements GlobalFilter, Ordered {

    @Value("${whiteList}")
    private String whiteList;

    @Autowired
    private RemoteSsoService remoteSsoService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


         //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        //获取response对象
        ServerHttpResponse response = exchange.getResponse();
        //获取请求的路径
        RequestPath path = request.getPath();
        System.out.println("请求路径："+path);
        //获取白名单的字符串数组
        String[] whiteArray = whiteList.split(",");
        //循环遍历
        for (String allowAccessPath : whiteArray) {
            //如果包含，就直接放行
            if(path.toString().contains(allowAccessPath)){
                //直接放行
                return chain.filter(exchange);
            }
        }
        //获取token值
        //1，获取所有的请求参数
        //获取请求的所有参数 请求地址  uri?a=1&b=2&c=3&d=4&e=[1,2,3]&token=afdfadfa
        MultiValueMap<String, String> queryParamsMap = request.getQueryParams();
        //获取map中key和value  ['token':'["admin12313AFADFA23RASF-F2431"]','b':["2"]...'e':[1,2,3]]
        Set<Map.Entry<String, List<String>>> entrySet = queryParamsMap.entrySet();
        //定义是否含有token,如果含有获取token值
        String tokenTemp = null;
        //循环遍历
        for (Map.Entry<String, List<String>> mapEntry : entrySet) {
            String paramName = mapEntry.getKey();
            String paramValue =mapEntry.getValue().get(0);
            //System.out.println(paramName+"----------"+paramValue);
            if(paramName.equals("token")){
                //把 token的值赋值给tokenTemp
                tokenTemp = paramValue;
                break;
            }
        }
//        判断token是否为空，判断是否正确
        Boolean tokenStatus = remoteSsoService.checkUser(tokenTemp);
        if(tokenTemp==null||!tokenStatus){
            //返回一个错误提示  好难啊
            Map  resultMap = new HashMap();
            resultMap.put("code",5000);
            resultMap.put("message","token为空或者token错误！");
            //定义返回数组
            byte[] bytes = null;
            try {
                //阿里fastjson提供把mapd对象转为json字符换， 再使用getBytes返回byte[] 防止中文乱码
                bytes = JSON.toJSONString(resultMap).getBytes("GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            //定义spring提供的数据缓冲区
            DataBuffer dataBuffer  =response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(dataBuffer));
        }

        //让程序继续运行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 5;
    }
}